package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import io.swagger.util.Json;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;


    /**
     * 用户下单
     * @param dto
     * @return
     */
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
        Long userID = BaseContext.getCurrentId();       //获取当前用户的ID

        //查询地址表，获取收货人信息
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        if (addressBook == null ){
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //查询用户表，获取用户相关你信息
        User user = userMapper.getById(userID);
        if (user == null){
            throw new OrderBusinessException(MessageConstant.USER_NOT_LOGIN);
        }

        //查询购物车表，获取购物车信息
        List<ShoppingCart> cartList = shoppingCartMapper.list(userID);
        if (cartList == null || cartList.size() == 0){
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //1.构造订单数据，存入order表中
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);      //拷贝属性值
        //补全缺失的属性值
        orders.setNumber(System.currentTimeMillis()+"");    //订单编号
        orders.setStatus(Orders.PENDING_PAYMENT);           //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        orders.setUserId(userID);                           //下单人id
        orders.setOrderTime(LocalDateTime.now());           //下单时间
        orders.setPayStatus(Orders.UN_PAID);                //支付状态 0未支付 1已支付 2退款
        orders.setPhone(addressBook.getPhone());            //收货人手机号
        orders.setAddress(addressBook.getDetail());         //收货人地址
        orders.setConsignee(addressBook.getConsignee());     //收货人姓名
        orders.setUserName(user.getName());                 //下单人姓名
        //调用mapper 插入订单数据
        ordersMapper.insert(orders);
        log.info("订单id为：{}",orders.getId());

        //2.构造订单明细数据，存入order_detail表中
        List<OrderDetail> orderDetailsList =new ArrayList<>();
        //遍历购物车数据，将购物车数据转为订单明细数据
        cartList.forEach(cart->{
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail,"id");
            //关联订单id
            orderDetail.setOrderId(orders.getId());
            orderDetailsList.add(orderDetail);      //将数据加入订单明细列表中
        });
        //批量插入订单明细数据
        orderDetailMapper.insertBatch(orderDetailsList);

        //3.清理购物车
        shoppingCartMapper.clean(userID);

        //构造OrderSubmitVO，并返回
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
//        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));

//        return vo;



    /////////////////////////////////////////////////////////////////

    //模拟支付成功---修改订单状态
    paySuccess(ordersPaymentDTO.getOrderNumber());
    //返回一个空对象即可
        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        Long userID = BaseContext.getCurrentId();       //获取当前用户的ID

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userID);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);

        //通过wedSocket向客户端浏览器推送消息type orderId content
        Map map =new HashMap();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","订单号："+outTradeNo);

        String json= JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 历史订单查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult page(OrdersPageQueryDTO dto) {
        Long userID = BaseContext.getCurrentId();

        //设置分页参数
        PageHelper.startPage(dto.getPage(), dto.getPageSize());

        //查询相关数据
                //查询订单信息
        dto.setUserId(userID);
        Page<OrderVO>  pageR = ordersMapper.list(dto);

                //循环遍历 查询订单明细信息
        pageR.getResult().forEach(orderVO -> {

          List<OrderDetail>  orderDetailList = orderDetailMapper.listByOrderId(orderVO.getId());
          //将查询到的订单明细信息封装到orderVO中
          orderVO.setOrderDetailList(orderDetailList);
        });

        //封装PageResult并返回结果
        return new PageResult(pageR.getTotal(),pageR.getResult());
    }

    /**
     * 订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO getById(Long id) {
        //查询订单表
        Orders orders = ordersMapper.getByID(id);

        //查询订单明细表
        List<OrderDetail> orderDetailList = orderDetailMapper.listByOrderId(id);

        //封装OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 取消订单(用户端)
     *
     * @param id
     */
    @Override
    public void cancel(long id) {
        ordersMapper.upOrderStatus(id,Orders.CANCELLED);
    }


    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Integer id) {
        //查询当前订单中的订单明细（订单明细表）
           List<OrderDetail> orderDetailList  = orderDetailMapper.listByOrderId(id);
        ShoppingCart cart = new ShoppingCart();
        //循环遍历订单明细表，并插入到购物车表
           orderDetailList.forEach(orderDetail -> {
               BeanUtils.copyProperties(orderDetail,cart,"id");
               cart.setCreateTime(LocalDateTime.now());
               cart.setUserId(BaseContext.getCurrentId());
               log.info("");
               //调用mapper
               shoppingCartMapper.insert(cart);
           });
    }

    /**
     * 管理端订单查询
     * @param dto
     * @return
     */
    @Override
    public PageResult pageAdmin(OrdersPageQueryDTO dto) {
        //1.设置分页参数
        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        //2.查询订单数据
        Page<OrderVO> list = ordersMapper.list(dto);

            //查询订单菜品信息，并封装到OrderVO中
        list.getResult().forEach(orders ->{
           String orderDishes =orderDetailMapper.getDishByid(orders.getId());
                    //将查询到的订单里的菜品信息封装到OrderVO中
            orders.setOrderDishes(orderDishes);
        });
        //封装PageResult并返回

        return new  PageResult(list.getTotal(),list.getResult());
    }

    /**
     * 各个状态的订单数量统计
     */
    @Override
    public OrderStatisticsVO countByStatus() {
        OrderStatisticsVO statisticsVO = new OrderStatisticsVO();
        //设置待派送数量
        statisticsVO.setConfirmed(ordersMapper.countStatus(Orders.CONFIRMED));
        //设置待接单数量
        statisticsVO.setToBeConfirmed(ordersMapper.countStatus(Orders.TO_BE_CONFIRMED));
        //设置派送中数量
        statisticsVO.setDeliveryInProgress(ordersMapper.countStatus(Orders.DELIVERY_IN_PROGRESS));

        return statisticsVO;
    }

    /**
     * 商家接单
     * @param dto
     */
    @Override
    public void confirm(OrdersConfirmDTO dto) {
        dto.setStatus(Orders.CONFIRMED);
        ordersMapper.upOrderStatus(dto.getId(), dto.getStatus());
    }

    /**
     * 商家拒单
     * @param dto
     */
    @Override
    public void rejetion(OrdersRejectionDTO dto) {
            ordersMapper.reje(dto);
    }

    /**
     * 管理端取消订单
     * @param dto
     */
    @Override
    public void cancelAdmin(OrdersCancelDTO dto) {
        ordersMapper.canaelORadmin(dto);
    }

    /**
     * 订单派送
     * @param id
     */
    @Override
    public void delivery(Long id) {
        ordersMapper.deliOrder(id);
    }

    /**
     * 订单完成
     * @param id
     */
    @Override
    public void complete(Long id) {
        ordersMapper.complete(id);
    }

    /**
     * 订单催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        //根据ID查询订单
        Orders orders = ordersMapper.getByID(id);

        //校验订单是否存在
        if (orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //通过wedSocket向客户端浏览器推送消息type(1为来单提醒；2为客户催单) orderId content
        Map map =new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号："+orders.getNumber());

        webSocketServer.sendToAllClient(JSON.toJSONString(map));

    }

}
